import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {AppAuthService} from './server/app-auth.service';
import {Injectable} from '@angular/core';
import {Demejimmer_constants} from './const/demejimmer_constants';
import {from, lastValueFrom, Observable} from 'rxjs';


/**
 * Http前置 HttpInterceptor  暂时没用 使用时 在ApplicationConfig 配置
 *  provideHttpClient(withInterceptors([httpapiinterceptorInterceptor]))
 */

@Injectable({
  providedIn: 'root'
})
export class DemoJimmerHttpInterceptor implements HttpInterceptor {
  constructor(private appAuthService: AppAuthService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.httpapiinterceptorInterceptor(req, next));
  }

  async httpapiinterceptorInterceptor(req: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {

    //1无需登录就能访问的  验证跳过的集合
    if (Demejimmer_constants.NoneInterceptorUrls.find(value => value == req.url)) {
      return lastValueFrom(next.handle(req));
    }

    const loggedInfo = await this.appAuthService.isLoggedIn();
    //2需要登录的
    if (loggedInfo === false) {
      throw new Error('没有登录,无法使用token');
    }

    // 2.2 统一处理的url
    const tokenS = loggedInfo.find(toke => toke.name === Demejimmer_constants.TokenS);
    if (tokenS === undefined || tokenS.jwtToken === undefined) {
      throw new Error('tokenS异常,无法使用TokenS');
    }

    //req.clone 赋值新的token
    const newReq = req.clone({
      headers: req.headers.set('token', tokenS.jwtToken)
    });
    return lastValueFrom(next.handle(newReq));
  }
}
